package android.pot.com.smartcar.ui.register;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.pot.com.smartcar.R;
import android.pot.com.smartcar.action.Action;
import android.pot.com.smartcar.base.AppManager;
import android.pot.com.smartcar.base.MyResponseHandler;
import android.pot.com.smartcar.base.swipe.SwipeBackActivity;
import android.pot.com.smartcar.fragment.CallDialogView;
import android.pot.com.smartcar.tool.LoadingTool;
import android.pot.com.smartcar.tool.TipToast;
import android.pot.com.smartcar.ui.login.LoginsActivity;
import android.pot.com.smartcar.util.RegexUtils;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhaoshilu on 2017/11/29.
 */
public class RegistersActivity extends SwipeBackActivity {


    private EditText et_password;

    private EditText et_sure_password;

    private EditText et_phone;

    private EditText et_code;

    private EditText et_refer_num;


    private TextView tv_getcode;

    private TimerTask timerTask;

    private int second = 70;

    private Timer timer;

    private String verifyCode;

    private String url,title;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        AppManager.getAppManager().addActivity(this);
        initView();
        addListener();
        initData();

    }

    protected void initView() {
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("注册");

        et_password = (EditText) findViewById(R.id.et_password);
        et_sure_password = (EditText) findViewById(R.id.et_sure_password);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_code = (EditText) findViewById(R.id.et_code);
        tv_getcode = (TextView) findViewById(R.id.tv_getcode);
        et_refer_num = (EditText) findViewById(R.id.et_refer_num);


    }

    protected void addListener() {

        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToFinishActivity();
            }
        });
        findViewById(R.id.ll_register_protocol).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!TextUtils.isEmpty(url)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    bundle.putString("title", title);
                    startAct(RegistersActivity.this, RegisterProtocolActivity.class, bundle);
                }
            }
        });
        findViewById(R.id.bt_register).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                verifyData();
            }
        });
        tv_getcode.setOnClickListener(new ObtainCodeListener());
        setEditTextInhibitInputSpeChat(et_password);
        setEditTextInhibitInputSpeChat(et_sure_password);

    }


    /**
     * 禁止EditText输入特殊字符
     * @param editText
     */
    public void setEditTextInhibitInputSpeChat(EditText editText){

        InputFilter filter=new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String speChat="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if(matcher.find())return "";
                else return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    protected void initData() {
        getProtocol();
    }


    private void reSend() {
        second = 90;
        cleanSendTimerTask();
        tv_getcode.setEnabled(true);
        et_phone.setEnabled(true);
        tv_getcode.setBackgroundResource(R.drawable.selector_black_btn);
        tv_getcode.setText("重新发送");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cleanSendTimerTask();
        AppManager.getAppManager().finishActivity();
    }

    private void getProtocol(){
        Map<String, String> params = new HashMap<String, String>();
        params.put("protocol_id", "2");

        Action.get().protocol_detail(this, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message,JSONObject response) {
                try {
                    title = response.getString("title");
                    url = response.getString("url");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        });
    }

    private void cleanSendTimerTask() {
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
    }

    Handler timehandler = new Handler() {
        public void handleMessage(Message msg) {
            if (second != 0) {
                tv_getcode.setEnabled(false);
                et_phone.setEnabled(false);
                tv_getcode.setBackgroundResource(R.drawable.corner_gray_bg);
                second--;
                tv_getcode.setText(second + "");
            } else {
                reSend();
            }
        }

        ;
    };


    private void sendCode(){
        if (TextUtils.isEmpty(et_phone.getText().toString())) {
            TipToast.show( "请输入手机号");
            return;
        } else {
            if (!RegexUtils.checkMobile(et_phone.getText().toString())) {
                TipToast.show("请输入正确手机号");
                return;
            }
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("phone", et_phone.getText().toString());
        Action.get().sendCode(this, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message,JSONObject response) {
                try {
                    verifyCode =  response.getString("auth_code");

                } catch (Exception e) {
                }
                timerTask = new TimerTask() {

                    @Override
                    public void run() {
                        Message msg = new Message();
                        msg.what = 0;
                        timehandler.sendMessage(msg);
                    }
                };

                timer = new Timer();
                tv_getcode.setTextSize(14);
                tv_getcode.setText(second + "");
                timer.schedule(timerTask, 0, 1000);
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                if (statusCode == 4003){//已注册
                    reSend();
                }
            }
        });

    }

    public class ObtainCodeListener implements View.OnClickListener {

        @Override
        public void onClick(View arg0) {
            sendCode();
        }
    }





    private void verifyData(){

        if (TextUtils.isEmpty(et_phone.getText().toString())) {
            TipToast.show( "请输入手机号");
            return;
        } else {
            if (!RegexUtils.checkMobile(et_phone.getText().toString())) {
                TipToast.show( "请输入正确手机号");
                return;
            }
        }
        if (TextUtils.isEmpty(et_code.getText().toString())) {
            TipToast.show("请输入验证码");
            return;
        }else{
            if(et_code.getText().toString().length()<6){
                TipToast.show("请输入6位的验证码");
                return;
            }
        }
        if (TextUtils.isEmpty(et_password.getText().toString())) {
            TipToast.show("请设置密码");
            return;
        } else {
            //6-16 数字加字母 特殊字符
            if (et_password.getText().toString().trim().length()<6 || et_password.getText().toString().trim().length()>12) {
                TipToast.show("请设置6-12位密码");
                return;
            }
        }
        if (TextUtils.isEmpty(et_sure_password.getText().toString())){
            TipToast.show("请输入确认密码");
            return;
        }

        if (!et_password.getText().toString().equals(et_sure_password.getText().toString())){
            TipToast.show("两次密码不一致，请重新输入");
            return;
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("phone", et_phone.getText().toString());
        params.put("password", et_password.getText().toString());
        params.put("password_confirm", et_password.getText().toString());
        params.put("auth_code", et_code.getText().toString());
        if (!TextUtils.isEmpty(et_refer_num.getText().toString())) {
            params.put("promotion_code", et_refer_num.getText().toString());
        }
        LoadingTool.StartLoading(this);
        Action.get().register(this, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message,JSONObject response) {
                CallDialogView dialogView = new CallDialogView(RegistersActivity.this,"恭喜您，账号注册成功");
                dialogView.show(getSupportFragmentManager(),"dialogView");
                dialogView.setMethodClickListener(new CallDialogView.OnMethodClickListener() {
                    @Override
                    public void methodClick() {
                        LoadingTool.EndLoading(RegistersActivity.this);
                        startAct(RegistersActivity.this, LoginsActivity.class);
                        AppManager.getAppManager().finishAllActivity();
                    }
                });
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
//                if (statusCode == 4002){
                    reSend();
//                }
            }
        });

    }

}